package kr.hkit.androidcomplete03.ch22;

import java.util.ArrayList;

import kr.hkit.androidcomplete03.R;
import android.app.ActionBar;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;

public class MyView extends View {
	
	Bitmap backImg;
	ArrayList<Ball> ballLists;
	final static int DELAY = 50;
	
	public MyView(Context context) {
		super(context);
		
		 ballLists = new ArrayList<Ball>(); 
		 backImg = BitmapFactory.decodeResource(context.getResources(), R.drawable.mingyeong);
		 mHandler.sendEmptyMessageDelayed(0, DELAY);
	}
	
	// 새로운 볼 생성(화면 클릭시)
	public boolean onTouchEvent(android.view.MotionEvent event) {
		if(event.getAction() == MotionEvent.ACTION_DOWN){
			Ball newBall = Ball.create((int)event.getX(), (int)event.getY());
			ballLists.add(newBall);
			
			invalidate();
			return true;
		}
		return false;
	};
	
	//실시간 화면 그리기
	protected void onDraw(Canvas canvas) {
		Rect dst = new Rect(0, 0, getWidth(), getHeight());
		canvas.drawBitmap(backImg, null, dst, null);
		for(int idx = 0; idx < ballLists.size(); idx++){
			ballLists.get(idx).draw(canvas);
		}
	};
	
	// 공 이동 및 화면 무효화
	Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			Ball ball;
			for(int idx = 0; idx< ballLists.size(); idx++){
				ball = ballLists.get(idx);
				ball.Move(getWidth(), getHeight());
				if(ball.count>4){
					ballLists.remove(idx);
					idx--;
				}
			}
			
			invalidate();
			mHandler.sendEmptyMessageDelayed(0, DELAY); //0.05초 마다 계속 호출됨
			
		};
	};

}
